{% extends "base.html" %}
{% load staticfiles %}

{% block title %}分账户管理{% endblock %}

{% block styles %}
    <style>
        .fixed-table-body {
            height: 55% !important;
        }
    </style>

{% endblock %}

{% block content %}
    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-xs-12">
                <div class="nav-tabs-custom">
                    <ul class="nav nav-tabs">
                        <li class="active"><a href="#fa-icons" data-toggle="tab">分账户列表</a></li>
                    </ul>

                    <div class="tab-content ">
                        <div class="tab-pane active mailbox-messages" id="fa-icons">
                            <div class=" mailbox-messages">
                                <table class="table table-bordered table-striped table-hover" id="userTable">

                                </table>
                            </div>
                        </div>
                        <div class="tab-pane" id="glyphicons">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>



    <!-- UserModal content -->
    {# 分账户新增和修改#}
    <div class="modal fade" id="modal_backtest_detail" data-backdrop="static">
        <div class="modal-dialog" style="width: 450px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body" style="padding: 30px;height:auto">
                    <form>
                        <input type="text" style="display: none" id="modifyid">
                        <div style="margin-top:3%">
                            <label>用户代码</label>
                            <select class="opts form-control" name="customerid" id="customerid">
                                <option value="" selected>
                                    用户代码(必填)
                                </option>
                                {% for foo in customerid %}
                                    <option value="{{ foo }}">{{ foo }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div style="margin-top:3%">
                            <label>交易通道</label>
                            <select class="opts form-control" name="tdchannelid" id="tdchannelid">
                                {% for foo in tdchannelid %}
                                    <option value="{{ foo.channelid }}" class="{{ foo.channelid }}"
                                            name="{{ foo.apitype }}">{{ foo.channelid }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div style="margin-top:3%">
                            <label>行情通道</label>
                            <select class="opts form-control" name="mdchannelid" id="mdchannelid">
                                {% for foo in mdchannelid %}
                                    <option value="{{ foo }}">{{ foo }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div style="margin-top:3%">
                            <label>分账号代码</label>
                            <input class="opts form-control" type="text" name="accountid" required="" id="accountid"
                                   placeholder="分账号代码(必填)">
                        </div>
                        <div style="margin-top:3%">
                            <label>交易接口类型</label>
                            <select name="tdapitype" id="tdapitype" class="opts form-control">
                                <option value="1">CTP</option>
                                <option value="3">FEMAS</option>
                                <option value="4">SIM</option>
                                <option value="5">UFX</option>
                                <option value="6">CFETS</option>
                                <option value="7">SIP</option>
                                <option value="8">CFETS_xQuant</option>
                                <option value="9">MDCenter</option>
                                <option value="a">QBMD</option>
                            </select>
                        </div>
                        <div style="margin-top:3%">
                            <label>资金账号</label>
                            <input class="opts form-control" id="assetno" name="assetno" type="text"
                            >
                        </div>
                        <div style="margin-top:3%">
                            <label>持仓帐号</label>
                            <input class="opts form-control" id="combino" name="combino" type="text"
                            >
                        </div>
                        <div style="margin-top:3%;display: none" id="acid">
                            <label>UFX账户编号</label>
                            <input class="opts form-control" id="apiaccountid" name="apiaccountid" type="text"
                                   placeholder="UFX账户编号(必填)">
                        </div>
                        <div style="margin-top:3%;display: none" id="usid">
                            <label>UFX 股东代码</label>
                            <input class="opts form-control" id="apiinvestorid" name="apiinvestorid" type="text">
                        </div>
                        <div style="margin-top:3%">
                            <span style="margin-left:10%;cursor:pointer;padding:5px" class="btn-primary"
                                  onclick="sub(gets)">提交</span>
                            <span style="cursor:pointer;margin-left:60%;padding:5px" onclick="fad()"
                                  class="btn-success">取消</span>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    {#    分账户删除#}
    <div class="modal fade" id="modal_delete" data-backdrop="static">
        <div class="modal-dialog" style="width: 300px;background-color:#eee">
            <div class="modal-content">
                <div class="modal-body" style="padding:5px;height:80px;overflow:auto">
                    <div>
                        <p style="margin-top:10px;margin-left:5px;">是否确定删除分账户</p>
                        <div>
                            <span id="del" sid="" onclick="quit__()"
                                  style="padding:2px;cursor:pointer;float:right;margin-right:10px" class="btn-success">取消</span>
                            <span onclick="del_()" style="padding:2px;cursor:pointer;float:right;margin-right:10px"
                                  class="btn-success">确定</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {#    <!--交易通道和接口类型的绑定-->#}
    {#    <input  id="" type="text" style="display: none" value="{{ channel_api_list }}">#}
{% endblock %}

{% block scripts %}
    <script type="text/javascript">

        //分账号新增页面，TDApiType与TDChannelID同步展示
        $("#tdchannelid").on('change', function () {
            //将apitype藏在name属性中，然后和channelid绑定
            var channel_apitype = $("#tdchannelid option:selected").attr('name')
            $("#tdapitype").val(channel_apitype)
            $("#tdapitype").attr("disabled", "disabled")
            var tdchannelid = $("#tdchannelid").val()
            //后台发送ajax请求,然后根据交易通道返回userid，也就是实体账户中的交易账号
            var data = {"channelid": tdchannelid}
            $.post("{% url 'Manager:cchannel_userid' %}", data, function (r) {
                if (channel_apitype == "5") {
                    $("#acid").css('display', 'block')
                    $("#usid").css('display', 'block')
                    $("#assetno").val("")
                    $("#combino").val("")
                    $("#apiinvestorid").prev().text("UFX 股东代码")
                    $("#apiinvestorid").removeAttr("placeholder")
                    $("#apiaccountid").val("")
                    $("#apiinvestorid").val("")
                    $("#assetno").removeAttr("readonly")
                    $("#combino").removeAttr("readonly")
                    $("#combino").attr("placeholder", "持仓账号(必填)")
                    $("#assetno").attr("placeholder", "资金账号(必填)")
                } else if (channel_apitype == "8") {
                    $("#acid").css('display', 'none')
                    $("#usid").css('display', 'block')
                    $("#apiinvestorid").prev().text("交易员编码")
                    $("#apiinvestorid").attr("placeholder", "交易员编码(必填)")
                    $("#assetno").val(r)
                    $("#assetno").attr("readonly", "readonly")
                    $("#combino").val(r)
                    $("#combino").attr("readonly", "readonly")

                } else {
                    //资金账号和持仓账号默认展示
                    $("#assetno").val(r)
                    $("#assetno").attr("readonly", "readonly")
                    $("#combino").val(r)
                    $("#combino").attr("readonly", "readonly")
                    $("#acid").css('display', 'none')
                    $("#usid").css('display', 'none')

                }
            });

        })


        function gets() {
            var obj = {
                'id': $('#modifyid').val(),
                'customerid': $('#customerid').val(),
                'tdchannelid': $('#tdchannelid').val(),
                'mdchannelid': $('#mdchannelid').val(),
                'accountid': $('#accountid').val(),
                'tdapitype': $('#tdapitype').val(),
                'assetno': $('#assetno').val(),
                'combino': $('#combino').val(),
                'apiaccountid': $('#apiaccountid').val(),
                'apiinvestorid': $('#apiinvestorid').val(),
                'sum': '1'
            }
            var data = JSON.stringify(obj)
            return data;
        }


        function sub(func) {
            data = func();
            for (let key in JSON.parse(data)) {
                var item = JSON.parse(data)[key]
                if (
                    key != "id" && key != "sum" && key != "tdapitype" && key != "apiaccountid"
                    && key != "apiinvestorid" && Boolean(item) == false && $("#" + key).parent().css("display") === 'block'
                ) {
                    if (key == "tdchannelid") {
                        var flag = 1
                    } else if (key == "mdchannelid") {
                        if (flag == 1) {
                            alert("交易通道和行情通道不能同时为空")
                            return
                        }
                    } else if (key === "combino" || key === "assetno") {
                        console.log("长度是：", item.length)
                        if ($("#tdapitype").val() == "5") {
                            var title = $("#" + key).prev().text()
                            alert(title + "不能为空!")
                            return
                        }
                        if (Boolean($('#mdchannelid').val()) == true) {
                            break
                        }

                    } else {
                        var title = $("#" + key).prev().text()
                        alert(title + "不能为空!")
                        return
                    }

                }
                if (key == "apiinvestorid" &&
                    Boolean(item) == false && $("#" + key).prev().text() == "交易员编码" &&
                    $("#" + key).parent().css("display") === 'block') {
                    alert($("#" + key).prev().text() + "不能为空！")
                    return;
                }
                if (key == "apiaccountid" && Boolean(item) == false && $("#" + key).parent().css("display") === 'block') {
                    alert($("#" + key).prev().text() + "不能为空！")
                    return;
                }
                if (key === "combino" || key === "assetno"){
                    if (item.length > 16){
                            var title = $("#" + key).prev().text()
                            alert(title + "长度不能超过16!")
                            return
                        }
                }
            }
            $.post("{% url 'Manager:cchannel_modify' %}", data, function (r) {
                if (r == 'y') {
                    window.location.reload();
                } else {
                    alert(r)
                }
            });
        }

        function modify(id) {
            $('.modal-title').text('修改');
            $("#modifyid").val(id)
            $("#acid").css('display', 'none')
            $("#usid").css('display', 'none')
            $("#jyyno").css('display', 'none')
            $("#tdapitype").attr("disabled", "disabled")
            $("#combino").removeAttr("placeholder")
            $("#assetno").removeAttr("placeholder")
            $("#apiinvestorid").prev().text("UFX 股东代码")
            $("#apiinvestorid").removeAttr("placeholder")
            $("#combino").attr("placeholder", "持仓账号(必填)")
            $("#assetno").attr("placeholder", "资金账号(必填)")
            $("#assetno").attr("readonly", "readonly")
            $("#combino").attr("readonly", "readonly")
            {#$("#customerid").attr("readonly", "readonly");#}
            $.get("{% url 'Manager:cchannel_modify' %}", {'id': id}, function (r) {
                if (r) {
                    for (var key in r) {
                        if (r[key] == "5") {
                            $("#acid").css('display', 'block')
                            $("#usid").css('display', 'block')
                        }
                        if (r[key] == "8") {
                            $("#acid").css('display', 'none')
                            $("#usid").css('display', 'block')
                            $("#apiinvestorid").prev().text("交易员编码")
                            $("#apiinvestorid").attr("placeholder", "交易员编码(必填)")
                        }
                        if ($('#' + key)) {
                            $('#' + key).val(r[key]);
                        }
                    }
                }
            });
        };

        function create() {
            $('.modal-title').text('新建');
            $('.opts').val("");
            $("#tdapitype").attr("disabled", "disabled")
            $("#assetno").removeAttr("readonly")
            $("#combino").removeAttr("readonly")
            $("#acid").css('display', 'none')
            $("#usid").css('display', 'none')
            $("#combino").removeAttr("placeholder")
            $("#assetno").removeAttr("placeholder")
            $("#assetno").attr("readonly", "readonly")
            $("#combino").attr("readonly", "readonly")
        }

        function quit__() {
            $('#modal_delete').modal('hide');
        }

        function fad() {
            $('#modal_backtest_detail').modal('hide');
        }

        function _delete(d) {
            $('#modal_delete').modal('show');
            $('#del').attr('sid', d);
        }

        function del_() {
            d = $('#del').attr('sid');//该值是从js动态渲染删除里面拿到的，先_delete，再del_
            $.post("{% url 'Manager:cchannel_modify' %}", {'id': d, 'delete': 1}, function (r) {
                if (r == 'y') {
                    window.location.reload();
                } else {
                    alert(r)
                }
            });//post请求的回调函数，空值show"默认合约不可修改"，y值则删除后跳转。
        }

        function InitBootstrapTable(my_url, my_table_id, my_columns, my_filename) {
            $('#' + my_table_id).bootstrapTable('destroy').bootstrapTable({
                height:'500px',
                url: my_url,
                method: 'get',
                columns: my_columns,
                toolbar: '#toolbar',
                striped: true,
                cache: false,
                pagination: true,
                sortable: true,
                sortOrder: "asc",
                queryParams: function (pageRequest) {
                    return pageRequest;
                },
                sidePagination: "server",
                pageNumber: 1,
                pageSize: 10,
                pageList: [10, 25, 50, 100],
                search: true,      //这里的search是bootstrap内置的查询方法，同时可以发给后台做判断  
                strictSearch: false,
                showColumns: true,
                showRefresh: true,
                minimumCountColumns: 2,
                clickToSelect: true,
                uniqueId: "_id",
                showToggle: true,
                cardView: false,
                detailView: false,
                //showExport: true,
                buttonsAlign: "right",
                exportDataType: "all",
                exportTypes: ['excel'],
                Icons: 'glyphicon-export',
                exportOptions: {
                    fileName: my_filename,
                },
            })
        };
        my_columns = [

            {field: "id", title: "记录主键", visible: false},
            {field: "customerid_id", title: "用户代码"},
            {title: "交易通道", field: "tdchannelid_id"},
            {title: "行情通道", field: "mdchannelid_id"},
            {title: "分账号代码", field: "accountid"},
            {title: "交易接口类型", field: "tdapitype"},
            {title: "资金账号", field: "assetno"},
            {title: "持仓帐号", field: "combino"},
            {title: "UFX 账户编号", field: "apiaccountid"},
            {title: "UFX 股东代码", field: "apiinvestorid"},
            {
                title: "操作",
                field: 'option',
                formatter: function (value, row, index) {
                    return "<span onclick=\"modify('" + value + "')\" class='btn btn-success btn-xs btn-flat btn_operation' data-toggle='modal' data-target='#modal_backtest_detail'> <i class='fa fa-pencil'></i>修改</span> " + "&nbsp<span onclick=\"_delete('" + value + "')\" type='button' class='btn btn-danger btn-xs btn-flat btn_operation'> <i class='fa fa-pencil'></i>删除</span> ";
                }
            }
        ];
        InitBootstrapTable("{% url 'Manager:cchanneList' %}", "userTable", my_columns, "cchanneList");
        $('.fixed-table-toolbar').append("&nbsp <span onclick='create()' type='button' class='btn btn-success btn-xs btn-flat btn_operation' data-toggle='modal' data-target='#modal_backtest_detail'> <i class='fa fa-pencil'></i>新建</span>");

        $('.page-list').css('display', 'none');
        $('.pagination-info').css('display', 'none');
        $('*[placeholder="Search"]').attr('placeholder', '请输入分账号代码');
    </script>
{% endblock %}